package com.xg.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xg.frame.constant.UrlConstant;
import com.xg.frame.entity.R;
import com.xg.sys.entity.SysOrganizationEntity;
import com.xg.sys.entity.SysUserOrgEntity;
import com.xg.sys.service.SysOrganizationService;
import com.xg.sys.service.SysUserOrgService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
 * @author tzt
 * @date Created in 2021/8/23 14:34
 * @description：
 * @modified By：
 */
@Controller
@RequestMapping(UrlConstant.WEB_ADMIN_URL + "/org")
public class OrgController {
    @Resource
    private SysOrganizationService sysOrganizationService;
    @Resource
    private SysUserOrgService sysUserOrgService;

    @GetMapping
    public String index(Model model) throws Exception {
        //获取当前登录用户菜单（树）
        model.addAttribute("treeList", sysOrganizationService.treeForYkk());
        return "/sys/org/list";
    }

    @ResponseBody
    @GetMapping("/{id}")
    public R<SysOrganizationEntity> getById(@PathVariable Long id) {
        SysOrganizationEntity byId = sysOrganizationService.getById(id);

        JSONObject obj = new JSONObject();
        obj.put("org", byId);
        return R.ok().info(obj);
    }

    @PostMapping("save")
    @RequiresPermissions("org:save")
    @ResponseBody
    public R save(@NotNull SysOrganizationEntity entity) throws Exception {
        if (entity.getId() == null) {
            //新增机构
            sysOrganizationService.save(entity);
        } else {
            //修改
            sysOrganizationService.updateById(entity);
        }
        return R.ok();
    }

    @GetMapping("del")
    @RequiresPermissions("org:del")
    @ResponseBody
    public R del(@NotNull Long id) {
        List<SysOrganizationEntity> orgList = sysOrganizationService.getByParentId(id);
        if (CollectionUtils.isNotEmpty(orgList)) {
            return R.error().message("存在子机构,请先删除子机构!");
        }
        boolean result = sysOrganizationService.removeById(id);
        if (result) {
            sysUserOrgService.remove(
                    new LambdaQueryWrapper<SysUserOrgEntity>()
                            .eq(SysUserOrgEntity::getOid, id)
            );
        }
        return result ? R.ok() : R.error();
    }
}
